<?php
namespace wow\model\forum;


use \gnomephp\doctrine\Doctrine;
/**
 * When a user reads a thread, this entity will get updated / added.
 * @author peec
 * @Entity
 */
class ThreadRead{
	
	/**
	 * @Id @Column(type="integer")
	 */
	public $account_id;
		
	/**
	 * @Id
     * @ManyToOne(targetEntity="\wow\model\forum\Thread", cascade={"all"})
     * @JoinColumn(name="thread_id", referencedColumnName="id")
     * @var wow\model\forum\Thread
     */
    public $thread;
	
		
	/**
	 * @Column(type="datetime")
	 * @var \DateTime
	 */
	protected $lastUpdated;
    
	
	public function __construct($account_id, $thread){
		$this->account_id = $account_id;
		$this->thread = $thread;
		$this->update();
	}
	
	
	public function update(){
		$this->lastUpdated = new \DateTime("now");
	}
	
	
	public function hasNewChanges(){
		return $this->lastUpdated->getTimestamp() < $this->thread->getLastUpdated()->getTimestamp();
	}
	
	
	static public function getReaded($account_id, $thread){
		Doctrine::load();
		$qb = Doctrine::getEM()->createQueryBuilder();
		$qb->select('tr')
		->from('\wow\model\forum\ThreadRead', 'tr')
		->innerJoin('tr.thread','t');
		
		$qb->where('tr.account_id = ?1')
		->andWhere('t.id = ?2')
		->setParameter(1, $account_id)
		->setParameter(2, $thread->getID());
		
		$tr = $qb->getQuery()->getOneOrNullResult();
		return $tr;		
	}
	
	
	static public function read($account_id, $thread){
		$tr = self::getReaded($account_id, $thread);
		if (!$tr){
			$tr = new ThreadRead($account_id, $thread);
		}else{
			$tr->update();
		}
		
		
		Doctrine::getEM()->persist($tr);
		
		Doctrine::getEM()->flush();
		
		return $tr;
	}
	
}